<template>
  <div class="post-overview">
    <div class="back-button-container">
      <button class="back-button" @click="goBack">
        <i class="fa fa-arrow-left"></i> 返回首页
      </button>
    </div>
    <h2>内容总览</h2>
    <div class="search-bar">
      <input 
        type="text" 
        placeholder="搜索帖子..." 
        v-model="searchQuery" 
        @keyup.enter="search"
      />
      <button @click="search">搜索</button>
    </div>
    <div class="filter-options">
      <div class="category-filter">
        <label>分类:</label>
        <select v-model="selectedCategory">
          <option value="all">全部</option>
          <option value="tech">技术</option>
          <option value="life">生活</option>
          <option value="news">资讯</option>
          <option value="question">问答</option>
        </select>
      </div>
      <div class="sort-filter">
        <label>排序:</label>
        <select v-model="sortOption">
          <option value="latest">最新</option>
          <option value="hottest">最热</option>
          <option value="mostLiked">最多点赞</option>
          <option value="mostCommented">最多评论</option>
        </select>
      </div>
    </div>
    <div class="post-list">
      <div class="post-item" v-for="post in filteredPosts" :key="post.knowledgeId">
        <div class="post-header">
          <div class="user-info">
            <img :src="getUserAvatar(post.author)" alt="用户头像" class="avatar" />
            <div>
              <div class="username">{{ post.author }}</div>
              <div class="post-time">{{ formatDate(post.createdAt) }}</div>
            </div>
          </div>
          <div class="post-category" :class="getCategoryClass(post.category)">{{ post.category }}</div>
        </div>
        <div class="post-content">
          <h3 @click="viewPostDetails(post.knowledgeId)">{{ post.title }}</h3>
          <p>{{ post.content.substring(0, 150) }}{{ post.content.length > 150 ? '...' : '' }}</p>
          <div class="post-images" v-if="post.images && post.images.length > 0">
            <img v-for="(image, index) in post.images.slice(0, 3)" :key="index" :src="image" alt="帖子图片" class="post-image" />
          </div>
        </div>
        <div class="post-stats">
          <div class="stat-item" @click="toggleLike(post)">
            <i class="fa fa-thumbs-up" :class="{ 'liked': isPostLiked(post) }"></i>
            <span>{{ post.likes }}</span>
          </div>
          <div class="stat-item" @click="viewPostDetails(post.knowledgeId)">
            <i class="fa fa-comment"></i>
            <span>{{ post.comments ? post.comments.length : 0 }}</span>
          </div>
          <div class="stat-item" @click="toggleFavorite(post)">
            <i class="fa fa-star" :class="{ 'favorited': isFavorited(post) }"></i>
            <span>{{ post.favorites || 0 }}</span>
          </div>
          <div class="stat-item">
            <i class="fa fa-eye"></i>
            <span>{{ post.views || 0 }}</span>
          </div>
        </div>
      </div>
    </div>
    <div v-if="!filteredPosts.length" class="empty-state">
      <i class="fa fa-search"></i>
      <p>没有找到符合条件的帖子</p>
    </div>
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>{{ currentPage }} / {{ totalPages }}</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/user'
import { usePostStore } from '@/stores/post'
import { useUiStore } from '@/stores/ui'

const router = useRouter()
const route = useRoute()

const userStore = useUserStore()
const postStore = usePostStore()
const uiStore = useUiStore()

const { user, users } = storeToRefs(userStore)
const { allPosts } = storeToRefs(postStore)

const searchQuery = ref('')
const selectedCategory = ref('all')
const sortOption = ref('latest')
const currentPage = ref(1)
const postsPerPage = ref(5)

const refreshPosts = () => {
  currentPage.value = 1
  searchQuery.value = ''
  selectedCategory.value = 'all'
  sortOption.value = 'latest'
}

watch(
  () => route.query,
  () => {
    refreshPosts()
  },
  { immediate: true }
)

const filteredPosts = computed(() => {
  let posts = [...allPosts.value]

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    posts = posts.filter(post =>
      post.title.toLowerCase().includes(query) ||
      post.content.toLowerCase().includes(query) ||
      post.author.toLowerCase().includes(query)
    )
  }

  if (selectedCategory.value !== 'all') {
    posts = posts.filter(post => post.category === selectedCategory.value)
  }

  switch (sortOption.value) {
    case 'latest':
      posts.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
      break
    case 'hottest':
      posts.sort((a, b) => (b.views || 0) - (a.views || 0))
      break
    case 'mostLiked':
      posts.sort((a, b) => b.likes - a.likes)
      break
    case 'mostCommented':
      posts.sort((a, b) => (b.comments?.length || 0) - (a.comments?.length || 0))
      break
  }

  const start = (currentPage.value - 1) * postsPerPage.value
  return posts.slice(start, start + postsPerPage.value)
})

const totalPages = computed(() => {
  return Math.ceil(allPosts.value.length / postsPerPage.value) || 1
})

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

const getUserAvatar = (username) => {
  const found = users.value.find(u => u.username === username)
  return found ? found.avatar : 'https://picsum.photos/id/0/200/200'
}

const getCategoryClass = (category) => {
  const classes = {
    tech: 'bg-blue-100 text-blue-800',
    life: 'bg-green-100 text-green-800',
    news: 'bg-red-100 text-red-800',
    question: 'bg-yellow-100 text-yellow-800'
  }
  return classes[category] || 'bg-gray-100 text-gray-800'
}




const viewPostDetails = (postId) => {
  router.push({ name: 'PostDetail', params: { id: postId} })
}

const toggleLike = (post) => {
  if (!user.value) {
    uiStore.showNotification('错误：请先登录')
    return
  }
  console.log('✅ 点赞帖子：', post.knowledgeId, '当前用户：', user.value.userId)
  postStore.toggleLike(post.knowledgeId, user.value.userId)
}



const toggleFavorite = (post) => {
  const userId = user.value?.userId
  if (!userId) {
    uiStore.showNotification('错误：请先登录')
    return
  }
  console.log('✅ 收藏帖子：', post.knowledgeId, '当前用户：', userId)
  postStore.toggleFavorite(post.knowledgeId, userId)
}

const isFavorited = (post) => {
  const userId = userStore.user?.userId
  return post.favoritedBy?.includes(String(userId))
}

const isPostLiked = (post) => {
  const userId = userStore.user?.userId
  console.log(post.likedBy);
  return post.likedBy?.includes(String(userId))
}

const search = () => {
  currentPage.value = 1
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

const goBack = () => {
  router.push('/dashboard')
}

onMounted(() => {
  if (!user.value) {
    router.push('/login')
  }else {
    postStore.fetchAllPosts().then(() => {
      console.log("✅ 拉取帖子成功", allPosts.value)
    })
  }
})
</script>


<style scoped>
/* 样式保持不变，与原始代码一致 */
.post-overview {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-top: 0;
  color: #333;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-bar input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-bar button {
  padding: 10px 20px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-bar button:hover {
  background-color: #0b7dda;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.category-filter,
.sort-filter {
  display: flex;
  align-items: center;
  gap: 10px;
}

.category-filter label,
.sort-filter label {
  font-weight: 500;
}

.category-filter select,
.sort-filter select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.post-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.post-item {
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 6px;
  transition: box-shadow 0.3s;
}

.post-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.username {
  font-weight: 500;
}

.post-time {
  font-size: 12px;
  color: #666;
}

.post-category {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.post-content h3 {
  margin-top: 0;
  margin-bottom: 10px;
  cursor: pointer;
  color: #2c3e50;
}

.post-content h3:hover {
  text-decoration: underline;
}

.post-content p {
  margin: 0;
  color: #666;
}

.post-images {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.post-image {
  max-height: 100px;
  max-width: 150px;
  object-fit: cover;
  border-radius: 4px;
}

.post-stats {
  display: flex;
  gap: 20px;
  margin-top: 15px;
  color: #666;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}

.stat-item:hover {
  color: #2196F3;
}

.liked {
  color: #2196F3;
}

.favorited {
  color: #FFC107;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 20px;
  color: #ccc;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
}

.pagination button {
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button:hover {
  background-color: #e0e0e0;
}

.pagination button:disabled {
  background-color: #f9f9f9;
  color: #aaa;
  cursor: not-allowed;
}

.back-button-container {
  margin-bottom: 15px;
}

.back-button {
  background-color: #f0f0f0;
  color: #333;
  border: none;
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.back-button:hover {
  background-color: #ddd;
}

.back-button i {
  margin-right: 6px;
}

</style>